package hydrap2p.modulemanager;

import hydrap2p.helper.ServiceConnector;
import hydrap2p.helper.Utility;

import java.io.IOException;

import org.apache.thrift.TException;

public class Main {

	public static void main(String[] args)
	{
		ModuleController controller=new ModuleController();

		try {
			startServiceManager(controller);
		} catch (Exception e) {
			System.err.println("Could not start up HydraP2P core: "+e.getLocalizedMessage());
			controller.shutdown();
			return;
		}
		
		ModuleManagerServer server;
		try {
			server=new ModuleManagerServer(controller);
		} catch (IOException e) {
			System.err.println("Could not start up HydraP2P: "+e.getLocalizedMessage());
			controller.shutdown();
			return;
		}
		new AutostartModules(controller).start();
		server.start();
		
	}
	
	public static void startServiceManager(ModuleController controller) throws Exception
	{
		boolean muststart;
		// test that ServiceManager is alive
		try {
			ServiceConnector.getServiceManager().ping();
			muststart=false;
		} catch (Exception e1) {
			muststart=true;
			// Is not running
		}

		boolean working=false;
		if (muststart)
		{
			int timeout=50000;
			long starttime=System.currentTimeMillis();
			if (controller.getModuleInfo("ServiceManager", "local")==null)
			{
				throw new Exception("Could not find a valid ServiceManager configuration to start!");
			}
			controller.start("ServiceManager", "local");
			while (System.currentTimeMillis()<starttime+timeout && !working)
			{
				try {
					ServiceConnector.getServiceManager().ping();
					working=true;
				} catch (Exception e) {
					// Doesn't respond
				}
				if (controller.getStatus("ServiceManager", "local").getStatus()==ModuleStatusType.STOPPED)
				{
					throw new Exception("ServiceManager stopped unexpectedly");
				}
			}
			
			if (controller.getStatus("ServiceManager", "local").getStatus()==ModuleStatusType.STARTED && !working)
			{
				throw new Exception("ServiceManager seems to be running, but is not responding at port "+Utility.getManagerPort());
			}
		}
		
		if (working)
			controller.startPinger();
	}
	
	private static class AutostartModules extends Thread
	{
		private ModuleController controller; 
		public AutostartModules(ModuleController controller)
		{
			super();
			this.controller=controller;
		}
		
		@Override
		public void run()
		{
			controller.autostartAll();
		}
	}
}
